package day18;

import java.util.concurrent.locks.ReentrantReadWriteLock;

//测试读写锁
public class Demo {
    Object data; //假设这是共享数据
    //定义读写锁
    ReentrantReadWriteLock lock=new ReentrantReadWriteLock();
    public void read(){  //读取数据
        String name=Thread.currentThread().getName();
        lock.readLock().lock(); //获取读锁
        try {
            System.out.println(name+"开始读2S数据:"+data);
            Thread.sleep(2000);
            System.out.println(name+"结束读2S数据："+data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();  //释放读锁
        }
    }
    public void write(Object data){ //写入数据
        String name=Thread.currentThread().getName();
        lock.writeLock().lock(); //获取读锁
        try {
            System.out.println(name+"开始写入2S数据:"+data);
            Thread.sleep(2000);
            this.data=data; //给共享数据赋值
            System.out.println(name+"结束写入2S数据:"+data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();  //释放读锁
        }
    }

    public static void main(String[] args) {
        Demo d=new Demo();
        for (int i=0;i<3;i++){
            new Thread(()->{
                for (int j=0;j<5;j++){
                    d.read();
                }
            },"读"+i).start();
            new Thread(()->{
                for (int j=0;j<5;j++){
                    d.write(Math.random());
                }
            },"写"+i).start();
        }
    }
}
